
<template>
  <view class="music-app">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="nav-left">
        <text class="title">音乐盒子</text>
        <view class="user-info" v-if="user">
          <text class="welcome">欢迎，{{ user.nickname || user.username }}</text>
        </view>
      </view>
      <view class="nav-right">
        <image class="user-avatar" v-if="user" :src="user.avatar || defaultAvatar" mode="aspectFill" @click="goToMine"></image>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <input class="search-input" type="text" v-model="searchQuery" placeholder="搜索歌曲/歌手" confirm-type="search" @confirm="doSearch" />
      <button class="search-action" @click="doSearch">
        <image class="search-icon" src="/static/search.png" mode="aspectFit"></image>
      </button>
    </view>

    <!-- 轮播图区域 -->
    <view v-if="banners.length === 0" class="banner-placeholder">
      <text>轮播图加载中...</text>
    </view>
    <swiper v-else class="banner-swiper" indicator-dots autoplay interval="3000" duration="500" :touchable="true" :circular="true" @change="onBannerChange">
      <swiper-item v-for="(item, index) in banners" :key="index" @click="onBannerClick(item)">
        <image class="banner-image" :src="item.image" mode="aspectFit"></image>
      </swiper-item>
    </swiper>

    <!-- 功能快捷入口 -->
    <view class="quick-actions">
      <view class="action-item" v-for="(action, index) in quickActions" :key="index" @click="handleAction(action.type)">
        <image class="action-icon" :src="action.icon" mode="aspectFit"></image>
        <text class="action-label">{{ action.label }}</text>
      </view>
    </view>

    <!-- 歌曲列表（整页滚动） -->
    <view class="song-list-container">
      <view class="song-item" v-for="(song, index) in filteredSongs" :key="index">
        <image class="song-cover" :src="song.cover" mode="aspectFill" @click="goToPlayer(song)"></image>
        <view class="song-info" @click="goToPlayer(song)">
          <text class="song-title">{{ song.title }}</text>
          <text class="song-artist">{{ song.artist }}</text>
        </view>
        <text class="song-duration">{{ song.duration }}</text>
        <button class="fav-btn" @click.stop="toggleFavorite(song)">
          <image class="fav-icon" :src="isFavorite(song.id) ? '/static/shoucang-active.png' : '/static/shoucang.png'" mode="aspectFit"></image>
        </button>
        <button class="play-btn" @click.stop="togglePlay(song)">
          <image v-if="currentSong.id === song.id && isPlaying" class="play-icon" src="/static/stop.png" mode="aspectFit"></image>
          <image v-else class="play-icon" src="/static/start.png" mode="aspectFit"></image>
        </button>
      </view>
    </view>

    <!-- 底部播放控制条 -->
    <view class="player-bar" v-if="currentSong">
      <image class="player-cover" :src="currentSong.cover" mode="aspectFill" @click="goToPlayer(currentSong)"></image>
      <view class="player-info" @click="goToPlayer(currentSong)">
        <text class="player-title">{{ currentSong.title }}</text>
        <text class="player-artist">{{ currentSong.artist }}</text>
      </view>
      <view class="player-controls">
        <button class="control-btn" @click="prevSong">
          <image class="control-icon" src="/static/before.png" mode="aspectFit"></image>
        </button>
        <button class="control-btn play-pause" @click="togglePlayback">
          <image v-if="isPlaying" class="play-pause-icon" src="/static/stop.png" mode="aspectFit"></image>
          <image v-else class="play-pause-icon" src="/static/start.png" mode="aspectFit"></image>
        </button>
        <button class="control-btn" @click="nextSong">
          <image class="control-icon" src="/static/next.png" mode="aspectFit"></image>
        </button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

// 数据定义
const banners = ref([])

const quickActions = ref([
  {
    type: 'favorites',
    label: '我的收藏',
    icon: 'https://ai-public.mastergo.com/ai/img_res/0115deff6fb3f0a186b74c37f6fd59f6.jpg'
  },
  {
    type: 'recent',
    label: '最近播放',
    icon: 'https://ai-public.mastergo.com/ai/img_res/7967f9db0f9dda07128d80e33e4ec3ad.jpg'
  },
  {
    type: 'rankings',
    label: '排行榜',
    icon: 'https://ai-public.mastergo.com/ai/img_res/fdd22db40b1ccadb4de5d4f4afee7ad9.jpg'
  },
  {
    type: 'artists',
    label: '歌手分类',
    icon: 'https://ai-public.mastergo.com/ai/img_res/78a09a6c603a75ffa1188012e9efbc3f.jpg'
  }
])

const songs = ref([])

// 获取歌曲列表
const fetchSongs = async () => {
  try {
    const res = await uni.request({
      url: 'http://localhost:3001/api/music',
      method: 'GET'
    })
    console.log('首页获取歌曲列表响应:', res)
    
    if (res.data && res.data.items && Array.isArray(res.data.items) && res.data.items.length > 0) {
      // 按照 id 升序排序，确保顺序一致
      const sortedItems = res.data.items.sort((a: any, b: any) => a.id - b.id)
      songs.value = sortedItems.map((song: any) => ({
        id: song.id,
        title: song.title,
        artist: song.artist,
        cover: song.cover,
        duration: formatDuration(song.duration || 180)
      }))
      console.log('首页使用后端歌曲列表，数量:', songs.value.length)
    } else {
      console.log('后端返回空数据，使用默认列表')
      // 使用默认列表
      songs.value = [
        {
          id: 1,
          title: '夜曲',
          artist: '周杰伦',
          cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
          duration: '3:45'
        },
        {
          id: 2,
          title: '青花瓷',
          artist: '周杰伦',
          cover: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg',
          duration: '3:20'
        },
        {
          id: 3,
          title: '稻香',
          artist: '周杰伦',
          cover: 'https://ai-public.mastergo.com/ai/img_res/346e24fb732344889d749f1d2fa20164.jpg',
          duration: '4:10'
        },
        {
          id: 4,
          title: '告白气球',
          artist: '周杰伦',
          cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
          duration: '3:34'
        },
        {
          id: 5,
          title: '七里香',
          artist: '周杰伦',
          cover: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg',
          duration: '4:05'
        }
      ]
    }
  } catch (err) {
    console.log('首页获取歌曲列表失败，使用默认列表:', err)
    // 使用默认列表
    songs.value = [
      {
        id: 1,
        title: '夜曲',
        artist: '周杰伦',
        cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
        duration: '3:45'
      },
      {
        id: 2,
        title: '青花瓷',
        artist: '周杰伦',
        cover: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg',
        duration: '3:20'
      },
      {
        id: 3,
        title: '稻香',
        artist: '周杰伦',
        cover: 'https://ai-public.mastergo.com/ai/img_res/346e24fb732344889d749f1d2fa20164.jpg',
        duration: '4:10'
      },
      {
        id: 4,
        title: '告白气球',
        artist: '周杰伦',
        cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
        duration: '3:34'
      },
      {
        id: 5,
        title: '七里香',
        artist: '周杰伦',
        cover: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg',
        duration: '4:05'
      }
    ]
  }
}

const searchQuery = ref('')
const filteredSongs = computed(() => {
  const q = searchQuery.value.trim().toLowerCase()
  if (!q) return songs.value
  return songs.value.filter(s =>
    s.title.toLowerCase().includes(q) ||
    s.artist.toLowerCase().includes(q)
  )
})

// 播放状态管理
const currentSong = ref<any>(null)
const isPlaying = ref(false)

// 方法定义
const goToSearch = () => {
  // 跳转到搜索页面逻辑
  console.log('跳转到搜索页面')
}

const goToMine = () => {
  uni.switchTab({ url: '/pages/mine/index' })
}

const handleAction = (type: string) => {
  // 处理快捷操作点击事件
  console.log(`点击了 ${type}`)
}

const goToPlayer = (song: any) => {
  // 直接跳转到播放页面
  uni.navigateTo({
    url: `/pages/player/index?song=${encodeURIComponent(JSON.stringify(song))}`
  })
}

const togglePlay = async (song: any) => {
  if (currentSong.value?.id === song.id) {
    isPlaying.value = !isPlaying.value
  } else {
    currentSong.value = song
    isPlaying.value = true
    // 记录播放历史
    await recordPlayHistory(song)
  }
  
  // 跳转到播放页面
  uni.navigateTo({
    url: `/pages/player/index?song=${encodeURIComponent(JSON.stringify(song))}`
  })
}

const togglePlayback = () => {
  isPlaying.value = !isPlaying.value
}

const prevSong = async () => {
  const currentIndex = songs.value.findIndex(song => song.id === currentSong.value?.id)
  if (currentIndex > 0) {
    const prevSong = songs.value[currentIndex - 1]
    currentSong.value = prevSong
    isPlaying.value = true
    await recordPlayHistory(prevSong)
  }
}

const nextSong = async () => {
  const currentIndex = songs.value.findIndex(song => song.id === currentSong.value?.id)
  if (currentIndex < songs.value.length - 1) {
    const nextSong = songs.value[currentIndex + 1]
    currentSong.value = nextSong
    isPlaying.value = true
    await recordPlayHistory(nextSong)
  }
}

onLoad(async () => {
  loadUser()
  // 启动时从后端加载轮播图
  fetchBanners()
  // 启动时从后端加载歌曲列表
  await fetchSongs()
  // 初始化默认播放第一首歌曲
  if (songs.value.length > 0) {
    currentSong.value = songs.value[0]
  }
})

// 监听页面显示，更新用户信息
onShow(() => {
  loadUser()
})

const loadUser = () => {
  const u = uni.getStorageSync('user')
  if (u && u.id) {
    user.value = u
    fetchFavorites()
  } else {
    user.value = null
    favoriteSet.value = new Set()
  }
}

const API_BASE_URL = 'http://localhost:3001'
const user = ref<any>(null)
const favoriteSet = ref<Set<number>>(new Set())
const defaultAvatar = 'https://ai-public.mastergo.com/ai/img_res/4f8c61af426b6e29d3c0f5ce2f9e1f66.jpg'

const formatDuration = (val: any) => {
  const n = Number(val)
  if (!isFinite(n) || n <= 0) return '3:00'
  const m = Math.floor(n / 60)
  const s = n % 60
  return `${m}:${String(s).padStart(2, '0')}`
}

const fetchBanners = async () => {
  console.log('开始获取轮播图数据...')
  try {
    const res = await uni.request({
      url: `${API_BASE_URL}/api/banners`,
      method: 'GET'
    })
    console.log('轮播图API响应:', res)
    const data = res?.data as any
    console.log('轮播图数据:', data)
    if (Array.isArray(data)) {
      banners.value = data
      console.log('轮播图数据设置成功，数量:', data.length)
    } else {
      console.log('轮播图数据不是数组格式')
    }
  } catch (e) {
    console.log('获取轮播图失败:', e)
    // 降级到默认轮播图
    banners.value = [
      {
        id: 1,
        image: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg'
      },
      {
        id: 2,
        image: 'https://ai-public.mastergo.com/ai/img_res/346e24fb732344889d749f1d2fa20164.jpg'
      }
    ]
    console.log('使用默认轮播图数据，数量:', banners.value.length)
  }
}

const doSearch = async () => {
  uni.vibrateShort && uni.vibrateShort()
  const q = searchQuery.value.trim()
  try {
    const res = await uni.request({
      url: `${API_BASE_URL}/api/music`,
      method: 'GET',
      data: { q }
    })
    const data = res?.data as any
    if (data && Array.isArray(data.items)) {
      // 将后端返回的歌曲渲染到列表
      songs.value = data.items.map((s: any, idx: number) => ({
        id: s.id ?? idx,
        title: s.title ?? '',
        artist: s.artist ?? '',
        cover: s.cover ?? 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
        duration: typeof s.duration === 'number' ? formatDuration(s.duration) : (s.duration ?? '3:00')
      }))
      return
    }
  } catch (e) {
    // 静默降级到本地过滤
  }
}

const fetchFavorites = async () => {
  if (!user.value?.id) return
  try {
    const res = await uni.request({ url: `${API_BASE_URL}/api/users/${user.value.id}/favorites`, method: 'GET' })
    const data = res?.data as any
    const ids = new Set<number>()
    if (Array.isArray(data?.items)) {
      for (const it of data.items) ids.add(Number(it.id))
    }
    favoriteSet.value = ids
  } catch {}
}

const isFavorite = (id: number) => favoriteSet.value.has(Number(id))

const recordPlayHistory = async (song: any) => {
  if (!user.value?.id) {
    console.log('用户未登录，不记录播放历史')
    return // 未登录用户不记录历史
  }
  
  console.log('开始记录播放历史:', {
    userId: user.value.id,
    musicId: song.id,
    title: song.title
  })
  
  try {
    const res = await uni.request({
      url: `${API_BASE_URL}/api/users/${user.value.id}/history`,
      method: 'POST',
      data: { 
        music_id: Number(song.id),
        play_duration: 0 // 这里可以记录实际播放时长
      },
      header: { 'content-type': 'application/json' }
    })
    console.log('播放历史记录成功:', song.title, res)
  } catch (err) {
    console.log('记录播放历史失败:', err)
  }
}

const toggleFavorite = async (song: any) => {
  if (!user.value?.id) {
    return uni.navigateTo({ url: '/pages/auth/login' })
  }
  const id = Number(song.id)
  try {
    if (favoriteSet.value.has(id)) {
      await uni.request({ url: `${API_BASE_URL}/api/users/${user.value.id}/favorites/${id}`, method: 'DELETE' })
      favoriteSet.value.delete(id)
      uni.showToast({ title: '已取消', icon: 'success' })
    } else {
      await uni.request({
        url: `${API_BASE_URL}/api/users/${user.value.id}/favorites`,
        method: 'POST',
        data: { music_id: id },
        header: { 'content-type': 'application/json' }
      })
      favoriteSet.value.add(id)
      uni.showToast({ title: '已收藏', icon: 'success' })
    }
  } catch {
    uni.showToast({ title: '操作失败', icon: 'none' })
  }
}

// 轮播图切换事件
const onBannerChange = (e: any) => {
  console.log('轮播图切换到第', e.detail.current + 1, '张')
}

// 轮播图点击事件
const onBannerClick = (item: any) => {
  console.log('点击了轮播图:', item.title)
  if (item.link) {
    // 如果有链接，可以跳转到对应页面
    uni.navigateTo({ url: item.link })
  } else {
    // 可以显示轮播图详情或执行其他操作
    uni.showToast({ title: item.title, icon: 'none' })
  }
}
</script>

<style>
page {
  height: 100%;
  overflow: auto; /* 允许整页滑动 */
}


/* 仅隐藏首页按钮的黑色边框 */
.search-btn, .search-action, .fav-btn, .play-btn, .control-btn {
  outline: none !important;
  border: none !important;
  box-shadow: none !important;
  -webkit-tap-highlight-color: transparent !important;
  -webkit-appearance: none !important;
  appearance: none !important;
}

.search-btn:focus, .search-action:focus, .fav-btn:focus, .play-btn:focus, .control-btn:focus {
  outline: none !important;
  border: none !important;
  box-shadow: none !important;
}

.search-btn:active, .search-action:active, .fav-btn:active, .play-btn:active, .control-btn:active {
  outline: none !important;
  border: none !important;
  box-shadow: none !important;
}

.music-app {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f8f9fa;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-left {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.user-info {
  margin-top: 8rpx;
}

.welcome {
  font-size: 24rpx;
  color: #666;
}

.user-avatar {
  width: 50rpx;
  height: 50rpx;
  border-radius: 25rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.search-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  outline: none;
}

.banner-swiper {
  width: 100%;
  height: 300rpx;
  flex-shrink: 0;
  cursor: pointer;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.banner-placeholder {
  width: 100%;
  height: 300rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f0f0;
  color: #999;
  font-size: 28rpx;
}

.banner-image {
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease;
}

.banner-swiper:hover .banner-image {
  transform: scale(1.05);
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 16rpx 30rpx;
  background: #ffffff;
  gap: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-input {
  flex: 1;
  height: 72rpx;
  background: #f5f6f7;
  border-radius: 36rpx;
  padding: 0 24rpx;
  font-size: 26rpx;
}

.search-action {
  height: 72rpx;
  padding: 0 28rpx;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 36rpx;
  outline: none;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.quick-actions {
  display: flex;
  justify-content: space-around;
  padding: 30rpx 0;
  background-color: #ffffff;
  margin-bottom: 20rpx;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 150rpx;
}

.action-icon {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 15rpx;
}

.action-label {
  font-size: 24rpx;
  color: #666666;
}

.song-list-container {
  flex: 1;
  padding: 0 30rpx;
}

/* 整页滚动时，不需要额外隐藏列表滚动条 */

.song-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eeeeee;
}

.song-cover {
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.song-cover:hover {
  transform: scale(1.05);
}

.song-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.song-title {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 10rpx;
}

.song-artist {
  font-size: 24rpx;
  color: #999999;
}

.song-duration {
  font-size: 24rpx;
  color: #999999;
  margin-right: 20rpx;
}

.play-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  outline: none;
}

.play-icon {
  width: 32rpx;
  height: 32rpx;
}

.fav-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0 10rpx 0 0;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  outline: none;
}

.fav-icon {
  width: 40rpx;
  height: 40rpx;
}

.player-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  bottom: 0;
  z-index: 100;
}

.player-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.player-cover:hover {
  transform: scale(1.1);
}

.player-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  cursor: pointer;
  padding: 10rpx;
  border-radius: 8rpx;
  transition: background-color 0.2s ease;
}

.player-info:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.player-title {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 5rpx;
}

.player-artist {
  font-size: 24rpx;
  color: #999999;
}

.player-controls {
  display: flex;
  align-items: center;
}

.control-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0 15rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  outline: none;
}

.control-icon {
  width: 28rpx;
  height: 28rpx;
}

.play-pause {
  background-color: #ff6b6b;
  border-radius: 50%;
  width: 70rpx;
  height: 70rpx;
}

.play-pause-icon {
  width: 36rpx;
  height: 36rpx;
}
</style>

